<template>
  <FullPageModal
    v-model:visible="modelVisible"
    :title="title"
    :custom-footer="true"
    :body-style="{ padding: 0 }"
    :inset-cls="insetCls"
    @ok="ok"
    @cancel="cancel"
    @open="open"
  >
    <div ref="content" class="h-full">
      <GroupPage
        group-title="设备点位"
        :has-content-title="false"
        class="p-0"
        group-title-class=" border-b-0"
        group-class="!border-0"
        group-content-class="border-0 border-r border-solid border-color-split pl-0 pt-0"
        group-size="small"
        @search="searchFn"
      >
        <template #extraButtons> </template>
        <template #group>
          <SpinSkeleton v-show="grpData.length > 0" :loading="grpLoading">
            <div class="w-full overflow-auto flex-1">
              <a-tree
                v-model:selectedKeys="selectedKeys"
                show-icon
                block-node
                :tree-data="(grpData as any)"
                :field-names="{
                  title: 'equipmentParamGroupsName',
                  key: 'equipmentParamGroupsId',
                }"
                @select="handleSelectTreeNode"
              >
                <template #icon="{ parentId }">
                  <Icon v-show="parentId === '0'" type="icon-xilie" class="text-2xl mr-4" />
                </template>
                <template #title="el">
                  <div class="w-full flex flex-row items-center icon-row">
                    <EllipsisText :max-len="10" :text="el.equipmentParamGroupsName" />
                  </div>
                </template>
              </a-tree>
            </div>
          </SpinSkeleton>
          <SlEmpty v-show="!grpLoading && grpData.length === 0" :description="emptyText"></SlEmpty>
        </template>
        <template #content>
          <div id="dragContainer" class="flex-1 overflow-hidden flex-row flex">
            <div class="w-2/3" style="height: calc(100% - 132px)">
              <div class="pl-4 h-36 flex flex-row items-end">
                <SearchForm
                  ref="searchIns"
                  :select-data="selectData"
                  :keyword-search-data="[{ label: '点位名称', key: 'searchText' }]"
                  :show-add-btn="false"
                  @search="searchFn"
                >
                  <template #extraButtons> </template>
                </SearchForm>
              </div>
              <SlTable
                class="mx-7 sl-pagination-px0"
                :columns="columns"
                row-key="equipmentAttributeId"
                :data-source="tableData"
                :loading="tableLoading"
                :scroll="{ x: true }"
                :search-model="searchModel"
                :ignore-keys="['equipmentTypeId', 'equipmentId', 'equipmentParamGroupsIdList']"
              >
                <template #bodyCell="{ column, record }">
                  <StateTag
                    v-if="column.dataIndex === 'bandStatus'"
                    :color="record.bandStatus ? '#38CE7B' : '#F56D6A'"
                    :value="record.bandStatus ? '已绑定' : '待绑定'"
                    class="h-6 ml-2 px-2"
                  ></StateTag>
                  <a-space v-if="column.key === 'oper'">
                    <!-- <PermissionBtn
                      v-if="!record.bandStatus"
                      :btn-props="{ type: 'link' }"
                      :oper-type="OperPermissionType.MANAGE"
                      @click="handleOper(record, 'band')"
                    >
                      绑定点位
                    </PermissionBtn> -->
                    <!-- <PermissionBtn
                      v-if="record.bandStatus"
                      :btn-props="{ type: 'link' }"
                      :oper-type="OperPermissionType.MANAGE"
                      @click="handleOper(record, 'change')"
                    >
                      换绑点位
                    </PermissionBtn> -->
                    <PermissionBtn
                      v-if="record.bandStatus"
                      :btn-props="{ type: 'link', danger: true }"
                      :oper-type="OperPermissionType.MANAGE"
                      class="text-red-400"
                      @click="handleOper(record, 'release')"
                    >
                      解除绑定
                    </PermissionBtn>
                  </a-space>
                  <div v-if="column.dataIndex === 'attributeName'" class="flex flex-row items-center">
                    <!-- <div class="pr-4" style="font-size: 0" @mousedown="sortStart($event, index)">
                      <Icon type="icon-tuodong" class="text-2xl cursor-move !text-color-secondary" />
                    </div> -->
                    <!-- <span>{{ record.attributeName }}</span> -->
                    <EllipsisText
                      class="text-color-active cursor-pointer"
                      :max-len="20"
                      :text="record.attributeName"
                      @click="handleView(record)"
                    />
                    <Icon v-show="record.keyAttribute" type="icon-wujiaoxing-2" class="!text-color-warn ml-2" />
                  </div>
                  <p v-if="column.dataIndex === 'attributeDisplayName'" class="w-32">{{
                    record.attributeDisplayName || "--"
                  }}</p>
                  <p v-if="column.dataIndex === 'equipmentParamGroupsName'" class="w-32">{{
                    record.equipmentParamGroupsName || "--"
                  }}</p>
                  <div
                    v-if="column.dataIndex === 'gatewayDatapointName'"
                    class="w-60 relative h-10 flex flex-row items-center"
                    draggable="true"
                    style="background-color: #f5f5f5"
                    :attr-id="record.equipmentAttributeId"
                  >
                    <p
                      :title="record.gatewayDatapointName"
                      class="m-0 pl-2 w-48 overflow-hidden !text-ellipsis whitespace-nowrap"
                      :attr-id="record.equipmentAttributeId"
                      style="color: #b9c0cc"
                      >{{ record.gatewayDatapointName || "拖动点位到这" }}</p
                    >
                    <Icon
                      v-if="record.bandStatus"
                      type="icon-shanchu"
                      class="text-color-disabled text-xl absolute right-4"
                      @click="handleOper(record, 'release')"
                    />
                    <!-- <a-input
                      v-model:value="record.gatewayDatapointName"
                      :attr-id="record.equipmentAttributeId"
                      placeholder="拖动点位到这"
                    >
                      <template #suffix>
                        <Icon
                          v-if="record.bandStatus"
                          type="icon-shanchu"
                          class="text-color-disabled text-xl pl-2"
                          @click="handleOper(record, 'release')"
                        />
                      </template>
                    </a-input> -->

                    <p class="hidden">{{ record.equipmentAttributeId }}</p>
                  </div>
                  <p v-if="column.dataIndex === 'readWriteType'" class="m-0">{{
                    ReadWriteType[record.readWriteType]
                  }}</p>
                  <p v-if="column.dataIndex === 'functionType'" class="m-0">{{ FunctionType[record.functionType] }}</p>
                  <EllipsisText
                    v-if="column.dataIndex === 'attributeDesc'"
                    :max-len="20"
                    :text="record.attributeDesc"
                  />
                </template>
              </SlTable>
            </div>
            <div class="w-1/3 flex flex-col border-0 border-l border-solid border-color-split px-4">
              <div class="h-36 flex flex-col justify-between">
                <p class="text-xl font-semibold text-color-main m-0 pt-6">网关点位</p>
                <a-input
                  v-model:value="pointName"
                  placeholder="搜索点位名称"
                  class="mb-2"
                  @keydown.enter="loadPointList"
                ></a-input>
              </div>
              <div
                class="flex flex-col pt-4 overflow-auto relative"
                style="height: calc(100% - 100px)"
                draggable="true"
              >
                <div
                  class="w-full h-17 py-4 flex flex-row items-center border-0 border-solid border-b border-color-split"
                >
                  <div class="flex-1 pl-2 font-semibold text-color-main">点位名称</div>
                  <div class="flex-1 font-semibold text-color-main">测点ID</div>
                </div>
                <div
                  v-for="item of pointList"
                  :key="item.gatewayDatapointId"
                  class="
                    hover:bg-color-split
                    w-full
                    mb-2
                    h-17
                    py-4
                    pl-2
                    point-item
                    flex flex-row
                    items-center
                    border-0 border-b border-solid border-color-split
                  "
                  draggable="true"
                  :gateway-id="item.gatewayDatapointId"
                  style="height: 60px"
                >
                  <div class="flex-1 point-row">{{ item.gatewayDatapointName }}</div>
                  <div class="flex-1 point-row">{{
                    item.datapointAttrs ? JSON.parse(item.datapointAttrs)["测点ID"] : "--"
                  }}</div>
                </div>
                <SlEmpty
                  v-show="pointList && pointList.length === 0"
                  class="absolute left-0 right-0 top-1/2"
                  :description="'暂无数据'"
                />
              </div>
            </div>
          </div>
        </template>
        <CURDDialog
          ref="grpIns"
          create-title="新增功能分组"
          update-title="编辑功能分组"
          delete-message="您确定要删除该功能分组"
          :show-options="grpShowOptions"
          :columns="grpColumns"
          :model="grpModel"
          :model-form-setting="gropModelFormSetting"
          :table-data="grpData"
          :curd="grpCurd"
          id-key="equipmentParamGroupsId"
          :reload-table="grpReloadTable"
        />

        <CURDDialog
          ref="functionIns"
          create-title="新增功能"
          update-title="编辑功能"
          delete-message="您确定要删除该功能吗？"
          :show-options="showOptions"
          :columns="(columns as any)"
          :model-form-setting="modelFormSetting"
          :model="model"
          :table-data="tableData"
          :curd="curd"
          id-key="equipmentTypeAttributeId"
          :reload-table="reloadTable"
          :get-delete-params="getUserDeleteParams"
          @before-ok="beforeOk"
          @ok="reloadTable"
        />
      </GroupPage>
    </div>
    <GatewayDatapointModal v-model:visible="datapointVisible" v-model:options="bandOption" @ok="reloadTable" />
    <EquipmentFunctionView v-model:function-attr-data="functionAttrData" :is-enterprise="true" />
  </FullPageModal>
</template>
<script lang="ts" setup>
import { nextTick, provide, ref, shallowRef, watch, computed, onMounted } from "vue";
import FullPageModal from "/@/components/FullPageModal.vue";
import {
  CURDAction,
  CURDModalEvent,
  FormItemComponentType,
  FormItemData,
  ShowCURDModalOptions,
} from "/@/components/CURDDialog/models";
import { OperPermissionType } from "/@/api/aiot/role/models";
import { message, Modal } from "ant-design-vue";
import { Api, bandEquipmentAttributes, unbandEquipmentAttributes } from "/@/api/aiot/equipmentType";
import {
  EquipmentAttrItem,
  ParEquipmentAttrItem,
  ParEquipmentTypeGroup,
  ReadWriteType,
  FunctionType,
} from "/@/api/aiot/equipmentType/models";
import { useEmptyText } from "/@/hooks/useEmptyText";
import { PatternKey } from "/@/utils/verify";
import { useRowDragSort } from "/@/hooks/useRowDragSort";
import { useCURD } from "/@/hooks/useCURD";
import { SelectItem } from "/@/types/components";
import InfoModal from "../../InfoModal";
import { GatewayModalPropsOptions } from "/@/api/aiot/equipment/models";
import { SearchFormKeywordKey } from "/@/types/components";
import { GatewayPointItem } from "/@/api/aiot/gateway/models";
import { gatewayDataPointsPage } from "/@/api/aiot/gateway";
import { findParent } from "/@/utils/dom";
import { loopItem } from "/@/utils/treeData";
import { OrderRule } from "/@/api/models";

const props = withDefaults(
  defineProps<{
    visible: boolean;
    options: GatewayModalPropsOptions;
    insetCls?: string | null | undefined;
  }>(),
  {
    insetCls: undefined,
  }
);

const emits = defineEmits(["create", "update:visible", "successFn"]);
const modelVisible = ref<boolean>(false);
const datapointVisible = ref<boolean>(false);
const addEquipmentAttrVisible = ref<boolean>(false);
const grpShowOptions = shallowRef<ShowCURDModalOptions>();
const curSelectedGroup = ref<ParEquipmentTypeGroup>({});
const selectedKeys = ref<string[]>([]);
const curEquipmentAttr = ref<ParEquipmentAttrItem>({});
const functionAttrData = ref<ParEquipmentAttrItem>({});
const grpIns = ref();
const functionIns = ref();
const { emptyText } = useEmptyText();
const keyword = ref<string>("");
const pointName = ref<string>("");
const pointNameTrim = computed(() => {
  return pointName.value.trim();
});
console.info("pointNameTrim", pointNameTrim.value);
const pointList = ref<GatewayPointItem[]>([]);
provide(SearchFormKeywordKey, keyword);
const columns = ref([
  {
    title: "点位名称",
    dataIndex: "attributeName",
    width: 120,
  },
  {
    title: "参数名称(显示名称)",
    dataIndex: "attributeDisplayName",
    width: 120,
  },
  {
    title: "参数分组",
    dataIndex: "equipmentParamGroupsName",
    width: 120,
  },
  {
    title: "绑定点位(拖入即绑定)",
    dataIndex: "gatewayDatapointName",
    width: 120,
  },
  // {
  //   title: "操作",
  //   key: "oper",
  //   width: 100,
  //   fixed: "right",
  // },
]);

const {
  curd: grpCurd,
  tableData: grpData,
  tableLoading: grpLoading,
  reloadTable: grpReloadTable,
} = useCURD<ParEquipmentTypeGroup>({
  getPageUrl: Api.equipmentGroupPage,
  createUrl: Api.addEquipmentParamGroups,
  updateUrl: Api.updateEquipmentParamGroups,
  deleteUrl: Api.deleteByIds,
  loadOnMounted: false,
});
const { curd, tableData, tableLoading, reloadTable, searchModel } = useCURD<ParEquipmentAttrItem>({
  getPageUrl: Api.equipmentAttrPage,
  // createUrl: Api.attrAdd,
  // updateUrl: Api.attrUpdate,
  // deleteUrl: Api.attrDel,
  loadOnMounted: false,
  pageSize: 999,
});
const { sortStart } = useRowDragSort({
  adjustNow: true,
  onSort(curRecord, targetRecord, isUp, curIndex, targetIndex) {},
  data: tableData,
});
const showOptions = ref<ShowCURDModalOptions>();
function setShowOptions(options: ShowCURDModalOptions) {
  showOptions.value = options;
}
function open(isFirstOpen) {
  if (isFirstOpen) {
    //第一次打开 加载数据
    nextTick(() => {
      // projectIns.value?.initFormItemComponentData();
    });
  } else {
    //之后每次打开 重置
    reset();
  }
}

watch(
  () => props.visible,
  async (v) => {
    modelVisible.value = v;
    if (v) {
      await grpReloadTable({ model: { equipmentTypeId: props.options.equipmentTypeId }, size: 999, current: 1 });
      if (grpData.value && grpData.value.length > 0) {
        // selectedKeys.value = [grpData.value[0].equipmentParamGroupsId || ""];
        reloadTable({
          model: {
            groupCode: "",
            equipmentTypeId: props.options.equipmentTypeId,
            equipmentId: props.options.equipmentId,
            searchText: "",
          },
        });
      }
      // 获取点位
      loadPointList();
      dragGeteway();
    } else {
      selectedFunctionKeys.value = [];
    }
  }
);
async function loadPointList() {
  // 获取点位
  pointList.value =
    (
      await gatewayDataPointsPage({
        model: { gatewayId: props.options.gatewayId, searchText: pointNameTrim.value },
        current: 1,
        size: 999,
        sort: "gatewayDatapointName",
        order: OrderRule.ASC,
      })
    )?.records || [];
}
const title = computed(() => {
  return `设备绑定点位（${props.options.equipmentName}）`;
});
const selectData = ref<SelectItem[]>([
  {
    label: "绑定状态",
    value: "all",
    key: "bandStatus",
    props: {},
    options: [
      { label: "全部", value: "all" },
      { label: "已绑定", value: "0" },
      { label: "待绑定", value: "1" },
    ],
  },
]);
watch(modelVisible, (v) => {
  emits("update:visible", v);
  if (!v) {
    pointName.value = "";
  }
});
function ondragstart(e) {
  console.log("开始拖拽");
  console.info("e", e);
}
function dragGeteway() {
  let equipmentAttributeId = "";
  let gatewayDatapointId = "";
  const containerDom: HTMLDivElement = document.querySelector("#dragContainer") as HTMLDivElement;
  console.info("dot1", containerDom);

  // ondragenter ondragover
  containerDom.ondragover = (e) => {
    e.preventDefault();
  };
  containerDom.ondrop = async (e: any) => {
    console.info("e==>", e);
    equipmentAttributeId = e?.target?.getAttribute("attr-id");
    if (!equipmentAttributeId) return;
    let req = await bandEquipmentAttributes({ equipmentAttributeId, gatewayDatapointId });
    if (req) {
      message.success("绑定成功");
      reloadTable();
    }
    console.info("req-->", req);
  };
  containerDom.ondragstart = (e: any) => {
    console.info("点击的数据", e);
    gatewayDatapointId = e?.target?.getAttribute("gateway-id");
    console.info("ondragstart===>", e.target.getAttribute("gateway-id"));
  };
  // req = await bandEquipmentAttributes({
  //   equipmentAttributeId: props.options?.equipmentAttributeId || "",
  //   gatewayDatapointId: row.gatewayDatapointId,
  // });
}
onMounted(() => {});
let selectedFunctionKeys = ref<string[]>([]);
const rowSelection = {
  onChange: (selectedRowKeys: string[], selectedRows: ParEquipmentAttrItem[]) => {
    selectedFunctionKeys.value = selectedRowKeys;
  },
  getCheckboxProps: (record: ParEquipmentAttrItem) => ({
    // disabled: record.name === "Disabled User", // Column configuration not to be checked
    // name: record.name,
  }),
};
function reset() {}
function searchFn({ searchText, bandStatus }) {
  let model: { searchText: string; bandStatus?: string | null | boolean } = { searchText, bandStatus };
  if (bandStatus === "all") {
    model.bandStatus = null;
  } else {
    // 0 已绑定 1 待绑定
  }
  model.bandStatus = bandStatus === "all" ? null : bandStatus === "0" ? true : false;
  reloadTable({ model });
}
function setFunctionGroupShowOptions(options: ShowCURDModalOptions) {
  grpShowOptions.value = options;
}
/**
 * ok cancel
 */
const content = shallowRef<HTMLDivElement>();
async function ok(isContinue) {}
function cancel() {
  emits("update:visible", false);
}
// 自定义删除用户方法
const getUserDeleteParams = (id) => {
  return id ? [id] : selectedFunctionKeys.value;
};
function beforeOk(e: CURDModalEvent) {
  if (e.model) {
    const model = e.model as ParEquipmentAttrItem;
    if (e.action === CURDAction.CREATE) {
      // model.dictionaryTypeId = curSelectedDicType.value?.dictionaryTypeId || "";
    }
  }
}
const model = ref<ParEquipmentAttrItem>({});
const modelFormSetting: FormItemData[] = [];
const grpColumns = ref([
  {
    title: "功能分组名称",
    dataIndex: "equipmentParamGroupsName",
    width: 100,
  },
  {
    title: "分组唯一标识",
    dataIndex: "equipmentParamGroupsCode",
    width: 100,
  },
  {
    title: "功能分组备注",
    dataIndex: "remark",
    width: 100,
  },
]);
const grpModel = ref<ParEquipmentTypeGroup>({
  equipmentParamGroupsName: "",
  equipmentParamGroupsCode: "",
  remark: "",
});
const gropModelFormSetting: FormItemData[] = [
  {
    key: "equipmentParamGroupsName",
    label: "分组名称",
    max: 32,
    required: true,
  },
  {
    key: "equipmentParamGroupsCode",
    label: "分组唯一标识",
    max: 32,
    required: true,
    labelDes: "支持大小写字母、数字和下划线",
    pattern: PatternKey.code,
    // pattern: PatternKey.name,
  },
  {
    key: "remark",
    label: "备注",
    max: 250,
    type: FormItemComponentType.TEXTAREA,
  },
  {
    key: "equipmentParamGroupsId",
    hide: true,
  },
];

function handleView(record: EquipmentAttrItem) {
  functionAttrData.value = record;
}
const bandOption = ref<GatewayModalPropsOptions>({
  equipmentAttributeId: "",
  gatewayId: "",
  gatewayTypeId: "",
});
const curGroupCode = ref<string>("");
const curEquipmentParamGroupsId = ref<string>("");
const equipmentParamGroupsIdList = ref<string[]>([]);
function handleSelectTreeNode(equipmentCategoryId, node) {
  // 保存当前选择的功能粉分组code
  keyword.value = "";
  curGroupCode.value = node.node.equipmentParamGroupsCode;
  curEquipmentParamGroupsId.value = node.node.equipmentParamGroupsId;
  equipmentParamGroupsIdList.value = [];
  let data: EquipmentAttrItem[] = [node.node];
  loopItem(data, (el, i, item) => {
    if (el.equipmentParamGroupsId) {
      equipmentParamGroupsIdList.value.push(el.equipmentParamGroupsId);
    }
  });
  reloadTable({
    model: {
      // groupCode: node.node?.equipmentParamGroupsCode || "",
      // equipmentParamGroupsId: node.node?.equipmentParamGroupsId || "",
      equipmentParamGroupsIdList: equipmentParamGroupsIdList.value,
      equipmentTypeId: props.options.equipmentTypeId,
      equipmentId: props.options.equipmentId,
      searchText: "",
    },
  });
}
async function handleOper(record, type) {
  if (type !== "release") {
    bandOption.value = {
      equipmentAttributeId: record.equipmentAttributeId,
      gatewayId: props.options.gatewayId,
      gatewayTypeId: props.options.gatewayTypeId,
    };
    datapointVisible.value = true;
  } else {
    InfoModal.confirm({
      content: "您确定解除绑定点位吗？",
      async onOk() {
        let req = await unbandEquipmentAttributes(record.equipmentAttributeId);
        if (req) {
          // message.success("操作成功");
          reloadTable();
        }
      },
    });
  }
}
function addFunc() {
  curEquipmentAttr.value = {};
  addEquipmentAttrVisible.value = true;
}
</script>
<style lang="less" scoped>
.show-edit:hover {
  .edit-block {
    display: block !important;
  }
}

:deep(.ant-tree .ant-tree-node-content-wrapper.ant-tree-node-selected) {
  background-color: rgba(66, 133, 244, 0.1);
}
:deep(.ant-tree.ant-tree-block-node .ant-tree-list-holder-inner .ant-tree-node-content-wrapper) {
  height: 44px;
  display: flex;
  align-items: center;
  width: 100%;
}
:deep(.ant-tree .ant-tree-node-content-wrapper .ant-tree-iconEle) {
  padding-top: 2px;
}
:deep(.ant-tree-switcher) {
  display: flex;
  flex-direction: row;
  align-items: center;
}
:deep(.ant-tree-title) {
  width: 100%;
}
.icon-row:hover {
  width: 100%;
  .icon-btn {
    display: block !important;
  }
}
.icon-btn {
  display: none;
}
.point-row {
  width: 90px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>
